<?

$name= preg_replace( '!\\.+!', '.', $_GET['name'] );
$debug= $_GET['debug'];
$root= '//' . $_SERVER['SERVER_NAME'] . strtr( dirname( $_SERVER['SCRIPT_NAME'] ), array( '\\' => '/' ) ) . '/';


function collect( $path ){
    if( !is_readable( $path ) ) return array();
    $data= file_get_contents( $path );
    if( !trim( $data ) ) return array( );
    $files= array( $path );
    preg_match_all( '/\$(?:\.\w+)+/', $data, $matches );
    if( !$matches ) return $files;
    foreach( $matches[0] as $expr ):
        $expr= strtr( substr( $expr, 2 ), array( '.' => '/' ) );
        while( true ){
            $file= $expr . '.js';
            if( $file !== $path ) $files= array_merge_recursive( collect( $file ), $files );
            if( !$expr ) break;
            $expr= preg_replace( '!(/|\w+)$!', '', $expr );
        };
    endforeach;
    return array_unique( $files );
};

$files= collect( $name . '.js' );

$buffer= array();
$buffer[]= "// <script type='text/javascript' style='display:block;white-space:pre;font-family:monospace'>";

if( $debug ):
    $buffer[]= "\n( function( path ){ document.write( '<script src=\"$root?path=' + path + '\" charset=\"utf-8\"></'+'script>' ); return arguments.callee } )\n";
    foreach( $files as $file ):
        $file= substr( $file, 0, -3 );
        $buffer[]= "( '$file' )\n";
    endforeach;
else:
    foreach( $files as $file ):
        $buffer[]= "\n" . file_get_contents( $file );
    endforeach;
endif;

$buffer[]= "\n// </script>\n";

header( 'Content-Type: text/html; charset=utf-8', true, 200 );
echo implode( '', $buffer );

?>
